﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebDownloader
{
    public static class Extensions
    {

        public static List<string> GetAttributeValues(this HTML.HtmlDocument pDocument, string pElementName, string pAttributeName, string pInnerTextRegEx)
        {
            var tList = new List<string>();

            var tElementList = pDocument.Nodes.FindByName(pElementName, true).Cast<HTML.HtmlNode>().Where(t => t is HTML.HtmlElement).Cast<HTML.HtmlElement>();

            var tFilteredElementList = tElementList.Where(t => t.Attributes.Cast<HTML.HtmlAttribute>().Where(j => j.Name.Equals(pAttributeName, StringComparison.CurrentCultureIgnoreCase) == true).Count() > 0);

            foreach (var tElement in tFilteredElementList)
            {

                var tAttribute = tElement.Attributes.Cast<HTML.HtmlAttribute>().Where(t => System.Text.RegularExpressions.Regex.IsMatch(t.Value, pInnerTextRegEx)).FirstOrDefault();

                if (tAttribute != null)
                {
                    tList.Add(tAttribute.Value);
                }
            }

            return tList;
        }

        public static List<HTML.HtmlElement> GetElements(this HTML.HtmlDocument pDocument, string pElementName, string pSubElementName)
        {
            var tElementList = pDocument.Nodes.FindByName(pElementName, true).Cast<HTML.HtmlNode>().Where(t => t is HTML.HtmlElement).Cast<HTML.HtmlElement>().ToList();
            var a = tElementList.Where(j => j.Nodes.FindByName(pSubElementName, false).Count != 0);
            var b = a.SelectMany(t => t.Nodes.Cast<HTML.HtmlNode>().Where(s => s is HTML.HtmlElement));
            var c = b.Cast<HTML.HtmlElement>();

            return c.ToList();
        }
    }
}
